package com.LeeCode;

/**
 * N 皇后 II
 */

public class Code052 {
    public static void main(String[] args) {
        int n = 8;
        System.out.println(new Code052().totalNQueens(n));
    }

    private int ans = 0;

    public int totalNQueens(int n) {
        int[] board = new int[n];
        backtrack(board, 0);
        return ans;
    }

    public void backtrack(int[] board, int row) {
        if (row == board.length) {
            ans++;
            return;
        }

        for (int col = 0; col < board.length; col++) {
            if (check(row, col, board)) {
                board[row] = col;
                backtrack(board, row + 1);
//                board[row] = 0;
            }
        }
    }

    public boolean check(int row, int col, int[] board) {
        for (int i = 0; i < row; i++) {
            if (col == board[i] || Math.abs(row - i) == Math.abs(col - board[i])) {
                return false;
            }
        }
        return true;
    }
}
